import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'

//导入路由
import VueRouter from 'vue-router'
Vue.use(VueRouter)
//导入路由的配置
import routes from './routes'

//导入前端存储工具
import store from './vuex/store'
//vue的扩展包
import Vuex from 'vuex'
Vue.use(Vuex)

//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
//NProgress.configure({ showSpinner: false });

//全局导入mockjs，生成假数据
// import Mock from './mock'
// Mock.bootstrap();

//字体图标：扩展elementui的图标库
import 'font-awesome/css/font-awesome.min.css'

/**
 * 全局导入axios
 */
import axios from 'axios'
axios.defaults.baseURL = "http://localhost:8080/"
Vue.prototype.$http = axios
Vue.prototype.fastdfsUrl = "http://121.37.194.36"

/**
 * axios的请求拦截器 拦截所有使用axios发送的ajax请求
 */
axios.interceptors.request.use(function (config) {
    //从localStorage中获取userToken
    let userToken = localStorage.getItem('userToken')
    if (userToken) {
        //给当前请求添加了一个请求头，请求头名称叫做 UserToken
        config.headers['UserToken'] = userToken;
    }
    return config;
}, function (error) {
    return Promise.reject(error);
});

/**
 * axios的响应拦截器  判断响应消息
 */
axios.interceptors.response.use(res=>{
    console.debug(res)
    if(!res.data.success && res.data.msg==="nouser"){
        app.$message.error("请先登录！")
        app.$router.push({path: '/login'});
    }
    return res;
},error => {
    Promise.reject(error);
})


/**
 * 全局导入Elementui
 */
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
Vue.use(ElementUI)


//创建路由对象
const router = new VueRouter({
    routes
})
//路由拦截器
router.beforeEach((to, from, next) => {
    //NProgress.start();
    if (to.path == '/login' || to.path == '/settledIn') {
        localStorage.removeItem('loginUser');
        localStorage.removeItem('userToken');
    }
    let user = JSON.parse(localStorage.getItem('loginUser'));
    if (!user && to.path != '/login' && to.path != '/settledIn') {
        next({ path: '/login' }) //访问的不是登录界面，但localStorage中没有当前用户对象，则跳转到登录页面
    } else {
        next()  //路由放行
    }
})

//router.afterEach(transition => {
//NProgress.done();
//});

let app = new Vue({
    el: '#app',
    //template: '<App/>',
    router,
    store,
    //components: { App }
    render: h => h(App)
})//.$mount('#app')
